{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 7138,  7138,  7138, 30926, 30926, 16700, 17819, 17819, 20326,\n",
       "         20326, 13225, 20326, 13225, 18195, 18195, 18195, 23446, 23446,\n",
       "         29536, 29536, 17493, 10321, 10321, 11592, 11592, 11592, 11592,\n",
       "         22077, 22077, 22077, 22077,  9846,  9846, 15087, 15087, 15087,\n",
       "         15087,  4958,  9770, 14318, 13092, 13092, 13092, 17021, 17021,\n",
       "         22868, 12202, 30796, 30796,  8231,  8231,   487,   487,   487,\n",
       "         14234, 19256, 19256, 16703, 16703, 16703, 11533, 11533, 23770,\n",
       "         20250, 17932, 17932, 17932, 17932, 16036, 16036, 16036, 16036],\n",
       "        [ 4810, 21134, 21134, 12884, 12884,  2289, 23218, 12934, 12934,\n",
       "         30626,  7836,  7836, 18581, 31832, 31832, 27922, 27922, 24678,\n",
       "         18531, 29712, 29712,    91, 24416, 24416, 24416, 24416, 24416,\n",
       "          9180,  6844,  6844,  6844,  6844, 30512, 30512, 30512, 30512,\n",
       "         30512, 15476, 15476,  3490,  3490,  3490, 11097, 11097, 10073,\n",
       "         10073, 10073, 10073, 22736, 22736, 20183, 20183, 13079, 13983,\n",
       "         13983,  8609, 25598, 24308, 24308,  4286,  4286, 14724, 14724,\n",
       "         29875, 29875, 29875,  7420,  7420,  7420,  7420,  7420,  7420],\n",
       "        [12409, 16914,  4032, 21129,  4032, 19797, 17947, 17947, 26180,\n",
       "         26180, 26235, 29470,  2256, 18503, 17039, 17039, 17039, 29536,\n",
       "         29536,  4129,  4129, 22773, 22773, 21197, 21197, 29536, 28891,\n",
       "         28891, 28891, 28891,  3700,  3700,  3700,  6681,  6681,  6618,\n",
       "          6618,  6618, 13490, 13490, 13490, 13490, 16780, 16780, 16780,\n",
       "         16780, 16780, 16780, 17713, 17713,  7017,  2015,  7017,  6553,\n",
       "         10561, 10561, 16309, 31561, 10371, 10371, 10371, 28050, 24597,\n",
       "         24597,  6286,  6286,  1912,  1912,  1912,  1912, 21678,   936],\n",
       "        [14627,  7653, 14627,  5135, 18905, 18905, 24607, 13086, 13086,\n",
       "         27983, 24607,  6276, 20658, 20658, 20658, 22980, 22980, 22980,\n",
       "         22980,  7526,  7526,  7526,  7526,  7526,  5962,  5962,  5962,\n",
       "          5962, 15027, 15027, 15027, 15027, 15027, 15027, 15027, 15027,\n",
       "         17515, 17515, 17515, 17040, 17040, 20994, 20994, 20994, 20994,\n",
       "          4339,  4339,  4339,  4339,  4339,  4339, 31999, 31999, 31999,\n",
       "         31999, 31999, 14586, 18158, 31813, 18158, 18158, 18158, 18158,\n",
       "         18158,   243,   243, 21429, 21429, 21429, 11348, 23026, 16238],\n",
       "        [28192,  4294,  4294,  3967,  3967, 16510,  3379,  3379,  3379,\n",
       "          6393, 20132, 12081, 12081, 12081,   765, 13339, 13339, 14770,\n",
       "         27041,  9413,  9413, 18627, 18627, 12311, 12311, 26237, 26237,\n",
       "         26237, 15904, 31221,  2866,  2866,  4513,  4513,  4513,  9238,\n",
       "          9238,  4513,  4513, 31277, 31277, 31277, 25142,  5405, 30288,\n",
       "         30288, 17677, 17677, 17677, 11563, 13202, 26252, 26252, 17801,\n",
       "         17801, 25065, 10161, 25065, 25065, 12822, 12822, 12822, 14821,\n",
       "         14821, 14821, 14821,  8028,  8028,  4584, 15205, 15205, 15205],\n",
       "        [ 2499,  2499, 13178, 13178,  2652,  2652, 26255, 26255, 26255,\n",
       "         31645, 29284, 22348, 22348, 22348, 31645,  6906,  6906,  6906,\n",
       "         31775, 31775, 29038, 29038, 10288, 24091, 24091, 23660, 23660,\n",
       "         23660, 26043, 26043,  2827,  2827, 16549, 16549, 29668, 31261,\n",
       "         30741, 27645, 31111, 23255, 23255, 23255, 23255,  5283,  5283,\n",
       "          5283, 10945, 10945, 10945, 10945, 10945, 31194, 31194, 31194,\n",
       "         31194, 31194, 31194, 31194,  7347,  7347,  7347,  7347,  3683,\n",
       "          3683, 30140, 30140, 18604, 18604,  6210, 11213, 11213,  7719],\n",
       "        [25637, 14718, 14718, 27833, 27833, 11007, 11007,  5411,  5411,\n",
       "          5411, 25637, 25637, 29430, 29430, 29430, 25213, 25213, 24206,\n",
       "          6751,  6751,  1278,  1278,  1278, 13664,  7840, 30487, 30487,\n",
       "         30487, 30487, 16505, 29060, 15463, 15463, 15463, 16024, 16024,\n",
       "         19299, 16700, 16700, 16737,  5864, 20509, 20509, 20509, 20509,\n",
       "         20042, 18633, 18633, 27572, 27572, 27572, 16700, 25029, 25029,\n",
       "         25029, 25029, 19787, 19787, 19787, 19787, 17236, 17236,  9719,\n",
       "          3825,  3825,  3825,  3825,  3825, 29173, 29173, 21505,  8762],\n",
       "        [ 2214,  2214,  2214, 14644, 18424, 18424, 28385, 28884, 28884,\n",
       "         28884,  5925,  5925,  5925,  5925,   328,   328,   328, 28869,\n",
       "         22185, 26287, 26287,  9605, 27854,  3847, 19388,  7742, 26473,\n",
       "         29625, 29625, 13886, 13886, 13886, 13464, 13464, 23525, 28324,\n",
       "         14461,  2613,  2613, 12488, 12488, 12488, 12488, 12488, 10071,\n",
       "         10071, 11971, 11971, 11971, 11971, 29192, 29192, 28220,  7380,\n",
       "          7380, 22200, 22200, 22200, 19388, 19388, 19388, 15756, 15756,\n",
       "         15756, 15756, 18015, 18015, 18015, 14225, 14225, 14225, 14225],\n",
       "        [24173, 26084, 26084,  2549,  2549,  2549,  2086,  2086,  2086,\n",
       "         16047, 20860, 21861, 21861, 20860, 20860, 30391, 30391, 30391,\n",
       "         30391, 30391, 23377, 23377, 19940, 19940, 19940, 19940, 27413,\n",
       "          6813,  6813,  6813,  4088,  5802,  5802,  5802,  7955,   328,\n",
       "           328, 14662,   328, 14662, 23479, 23479,  2694,  2694, 12343,\n",
       "         12343, 12246,  9099,  9099,  9099,  9099,  9099,  9099,  9099,\n",
       "          9099,  9099, 13511, 13511, 13511, 13511, 13511, 13511, 13511,\n",
       "         26239, 26239, 26239, 26239,   591, 10189, 21886, 22159, 22159],\n",
       "        [31378, 31378, 31378,  4600,  4600,    44,  5765, 29365, 16260,\n",
       "         16260, 16260, 16260,  9260,  9260,  9260,  9260,  9260,  9260,\n",
       "          9260,  9260,  9260, 16169, 16169, 16169, 16169,  2216, 19900,\n",
       "         19900, 19900, 19900, 16039, 12566,  8899, 12566,  9162,  9162,\n",
       "          9162,  9162, 27213,  9162, 27151, 27151, 31120, 31120,  2786,\n",
       "          2786, 31120, 18206, 18206,  6514,  6514,  6514,  6514,  6514,\n",
       "          2786, 14847, 14847,  6514,  6514,  6514,  6514,  6514,  6514,\n",
       "          2786, 30042,  6514, 22796, 28786, 28786, 20674, 20674, 20674]],\n",
       "       dtype=int32), 10.3734, 0.0]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.332, cost=4.11]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.36, cost=3.77] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.326948, training avg acc 0.217646\n",
      "epoch 1, testing avg loss 3.978739, testing avg acc 0.349156\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.471, cost=2.92]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.484, cost=2.77]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.417872, training avg acc 0.415222\n",
      "epoch 2, testing avg loss 3.075080, testing avg acc 0.458932\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:51<00:00,  2.40it/s, accuracy=0.55, cost=2.37] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.495, cost=2.52]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.752181, training avg acc 0.494466\n",
      "epoch 3, testing avg loss 2.768634, testing avg acc 0.496561\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.6, cost=2.02]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.554, cost=2.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.390676, training avg acc 0.539423\n",
      "epoch 4, testing avg loss 2.645435, testing avg acc 0.513939\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.64, cost=1.7]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.581, cost=2.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.138062, training avg acc 0.572631\n",
      "epoch 5, testing avg loss 2.601459, testing avg acc 0.522970\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.40it/s, accuracy=0.689, cost=1.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.565, cost=2.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.941493, training avg acc 0.599791\n",
      "epoch 6, testing avg loss 2.620469, testing avg acc 0.524573\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.713, cost=1.28]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.06it/s, accuracy=0.565, cost=2.32]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.776668, training avg acc 0.623748\n",
      "epoch 7, testing avg loss 2.663024, testing avg acc 0.523578\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.746, cost=1.1] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.581, cost=2.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.633322, training avg acc 0.645505\n",
      "epoch 8, testing avg loss 2.730652, testing avg acc 0.521451\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.40it/s, accuracy=0.762, cost=0.983]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.06it/s, accuracy=0.581, cost=2.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.510626, training avg acc 0.665169\n",
      "epoch 9, testing avg loss 2.786971, testing avg acc 0.520558\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.797, cost=0.845]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.05it/s, accuracy=0.559, cost=2.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.399681, training avg acc 0.683573\n",
      "epoch 10, testing avg loss 2.856899, testing avg acc 0.515471\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.41it/s, accuracy=0.817, cost=0.741]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.07it/s, accuracy=0.532, cost=2.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.301444, training avg acc 0.700200\n",
      "epoch 11, testing avg loss 2.961811, testing avg acc 0.509216\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.841, cost=0.65]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.05it/s, accuracy=0.559, cost=2.56]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.210598, training avg acc 0.716066\n",
      "epoch 12, testing avg loss 3.033276, testing avg acc 0.508951\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:51<00:00,  2.40it/s, accuracy=0.859, cost=0.593]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.04it/s, accuracy=0.57, cost=2.59] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.128234, training avg acc 0.730747\n",
      "epoch 13, testing avg loss 3.128496, testing avg acc 0.506283\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.86, cost=0.591] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.586, cost=2.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.060518, training avg acc 0.742980\n",
      "epoch 14, testing avg loss 3.224619, testing avg acc 0.503153\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.874, cost=0.509]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.548, cost=2.62]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.999509, training avg acc 0.754030\n",
      "epoch 15, testing avg loss 3.306164, testing avg acc 0.499372\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:50<00:00,  2.40it/s, accuracy=0.872, cost=0.503]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.15it/s, accuracy=0.554, cost=2.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.941365, training avg acc 0.765268\n",
      "epoch 16, testing avg loss 3.398814, testing avg acc 0.497000\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:49<00:00,  2.40it/s, accuracy=0.881, cost=0.46] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.554, cost=3]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.887443, training avg acc 0.775497\n",
      "epoch 17, testing avg loss 3.524017, testing avg acc 0.493447\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:51<00:00,  2.40it/s, accuracy=0.896, cost=0.403]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.01it/s, accuracy=0.543, cost=2.79]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.839406, training avg acc 0.785013\n",
      "epoch 18, testing avg loss 3.589927, testing avg acc 0.490498\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:51<00:00,  2.40it/s, accuracy=0.914, cost=0.366]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.05it/s, accuracy=0.532, cost=2.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.799431, training avg acc 0.793171\n",
      "epoch 19, testing avg loss 3.663480, testing avg acc 0.489732\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:48<00:00,  2.41it/s, accuracy=0.91, cost=0.331] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.09it/s, accuracy=0.538, cost=2.95]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.763683, training avg acc 0.800167\n",
      "epoch 20, testing avg loss 3.723958, testing avg acc 0.489388\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:20<00:00,  1.97it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.15195806"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
